//
//  ViewController.m
//  IOSLocation
//
//  Created by liulei on 2018/12/6.
//  Copyright © 2018年 www.icbc.com.cn. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "FovaLocationUtil.h"
#import "AFNetworking.h"
#import <arpa/inet.h>
#import "MKAnnotation.h"
#import <MapKit/MapKit.h>

@interface ViewController ()<CLLocationManagerDelegate,UIAlertViewDelegate,MKMapViewDelegate>{
    
}

@end

@implementation ViewController{
    UILabel *label;
    MKMapView *mapview;
    CLLocationManager *mgr;
    
    UIButton *buttonMax;
    UIButton *buttonSall;

}


- (void)viewDidLoad {
    
    [self MapView];
    
    [super viewDidLoad];
    label =[[UILabel alloc]initWithFrame:CGRectMake(20,40, [UIScreen mainScreen].bounds.size.width-60, 40)];
    label.textAlignment=NSTextAlignmentCenter;
    [self.view  addSubview:label];
    
    
    buttonMax =[[UIButton alloc]initWithFrame:CGRectMake(20, label.frame.origin.y+label.frame.size.height,80,40)];
    [buttonMax setTitle:@"放大" forState:UIControlStateNormal];
    [buttonMax setBackgroundColor:[UIColor redColor]];
    [buttonMax setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonMax addTarget:self action:@selector(zoomInClick:) forControlEvents:UIControlEventTouchUpInside];
    [mapview  addSubview:buttonMax];
    
    
    buttonSall =[[UIButton alloc]initWithFrame:CGRectMake(buttonMax.frame.origin.x+buttonMax.frame.size.width+120, label.frame.origin.y+label.frame.size.height,80,40)];
    [buttonSall setTitle:@"缩小" forState:UIControlStateNormal];
    [buttonSall setBackgroundColor:[UIColor redColor]];
    [buttonSall setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonSall addTarget:self action:@selector(zoomOutClick:) forControlEvents:UIControlEventTouchUpInside];
    [mapview  addSubview:buttonSall];

    //检测网络是否是可用正常连接网络服务器
   BOOL  b = [self socketReachabilityTest];
    if(b){
        [self getLocation];
        

    }else{

        [self showNetWordAlertMsg:[NSString stringWithFormat:@"您的网络不可用,点击设置网络"]];
    }
    
    
}

-(void)MapView{
    
    //1. 创建位置管理器
//    mgr = [CLLocationManager new];
//
//    //2. 请求授权 --> plist
//    if ([mgr respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
//        [mgr requestWhenInUseAuthorization];
//    }
    
    mapview = [[MKMapView alloc] initWithFrame:CGRectMake(0, buttonMax.frame.size.height+buttonMax.frame.origin.y+5, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [self.view addSubview:mapview];

    //3. 设置显示用户位置
    //Tracking: 跟踪
    /**
     MKUserTrackingModeNone = 0,
     MKUserTrackingModeFollow,             定位
     MKUserTrackingModeFollowWithHeading,  定位并且显示方向
     */
    mapview.userTrackingMode = MKUserTrackingModeFollow;
    
    //4. 设置代理 --> 获取用户位置信息
    mapview.delegate = self;
    
    
    /**
     iOS9新增属性
     */
    //1. 设置交通状况
    mapview.showsTraffic = YES;
    
    //2. 设置指南针(默认就是YES), 屏幕旋转后会出现, 如果点击会校正方向
   mapview.showsCompass = YES;
    
    //3. 设置比例尺
    mapview.showsScale = YES;
    //地图类型
    mapview.mapType = MKMapTypeStandard;
}
// 直接打开系统的设置界面
-(void)jumpToSettings
{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            }];
        }
    }
}
-(void)getLocation{
    [[FovaLocationUtil getInstance] getLocationAddressWithCallBack:^(NSArray *result, NSError *error) {
        if(error || result.count == 0){
            NSLog(@"error = %@",error);
            [self isLocationSuccessMsg:@"定位失败"];

        }else{
            
            CLPlacemark* placemark = result.firstObject;
            NSString *countryCode = [[placemark addressDictionary] objectForKey:@"CountryCode"];
            NSLog(@"countryCode:%@",countryCode);
            NSString *sysLangCode = [[NSLocale preferredLanguages] objectAtIndex:0];


            CLLocation *location=placemark.location;//位置
            CLRegion *region=placemark.region;//区域
            NSDictionary *addressDic= placemark.addressDictionary;//详细地址信息字典,包含以下部分信息
            NSString *name=placemark.name;//地名
            NSString *thoroughfare=placemark.thoroughfare;//街道
            NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息，例如门牌等
            NSString *locality=placemark.locality; // 城市
            NSString *subLocality=placemark.subLocality; // 城市相关信息，例如标志性建筑
            NSString *administrativeArea=placemark.administrativeArea; // 州
            NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息Street
            NSString *postalCode=placemark.postalCode; //邮编
            NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码
            NSString *country=placemark.country; //国家

            //设置label文本
            [label setText: [[[country stringByAppendingString:locality] stringByAppendingString:subLocality] stringByAppendingString:thoroughfare]];

        }
    }];
}

-(void)showNetWordAlertMsg:(NSString *)str{
    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag=121;
    [alert show];
}

-(void)isLocationSuccessMsg:(NSString *)str{
    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    alert.tag=123;
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView.tag==121){
        switch (buttonIndex) {
            case 0:
                // 取消
                NSLog(@"111");
                break;
                
            case 1:
                //确定
                NSLog(@"2");
                [self jumpToSettings];
                break;
        }
    }
    
}
//检测手机连接的是wifi 还是4 g
- (void)afnReachabilityTest {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 一共有四种状态
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"AFNetworkReachability Not Reachable");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"AFNetworkReachability Reachable via WWAN");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"AFNetworkReachability Reachable via WiFi");
                break;
            case AFNetworkReachabilityStatusUnknown:
            default:
                NSLog(@"AFNetworkReachability Unknown");
                break;
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

//检测网络是否是可以正常上网的网络
- (BOOL)socketReachabilityTest {
    // 客户端 AF_INET:ipv4  SOCK_STREAM:TCP链接
    int socketNumber = socket(AF_INET, SOCK_STREAM, 0);
    // 配置服务器端套接字
    struct sockaddr_in serverAddress;
    // 设置服务器ipv4
    serverAddress.sin_family = AF_INET;
    // 百度的ip
    serverAddress.sin_addr.s_addr = inet_addr("202.108.22.5");
    // 设置端口号，HTTP默认80端口
    serverAddress.sin_port = htons(80);
    if (connect(socketNumber, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) == 0) {
        close(socketNumber);
        return true;
    }
    close(socketNumber);;
    return false;
}

// *********************************MapView*********************************


#pragma mark 切换地图类型
- (void)mapTypeChangeClick:(UISegmentedControl *)sender {
    /**
     MKMapTypeStandard = 0,    默认
     MKMapTypeSatellite,       卫星
     MKMapTypeHybrid,          混合
     MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), 下面两个属性, 中国区无用
     MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
     */
    // 设置地图类型 , 一般要使用默认, 要么使用混个, 单纯的卫星图没有意义.
    switch (sender.selectedSegmentIndex) {
        case 0:
            mapview.mapType = MKMapTypeStandard;
            break;
        case 1:
            mapview.mapType = MKMapTypeSatellite;
            break;
        case 2:
            mapview.mapType = MKMapTypeHybrid;
            break;
        case 3:
            mapview.mapType = MKMapTypeSatelliteFlyover;
            break;
        case 4:
            mapview.mapType = MKMapTypeHybridFlyover;
            break;
            
        default:
            break;
    }
}

/**
 完成用户位置更新的时候 调用
 MKUserLocation : 大头针模型
 */
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //需求: 显示大头针信息 --> 反地理编码实现
    
    //1. 创建一个CLGeocoder对象
    CLGeocoder *geocoder = [CLGeocoder new];
    
    //2. 实现反地理编码方法
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        //3.1 防错处理
        if (placemarks.count == 0 || error) {
            return;
        }
        
        //3.2 获取对象
        CLPlacemark *placemark = placemarks.lastObject;
        
        //3.3 设置标题为城市信息
        userLocation.title = placemark.locality;
        
        //3.4 设置子标题为详细地址
        userLocation.subtitle = placemark.name;
        
        
        // 显示地图的显示区域
        CLLocationCoordinate2D center = userLocation.location.coordinate;
        
        // 设置区域跨度
        MKCoordinateSpan span = MKCoordinateSpanMake(0.0024545, 0.0014343);
        
        // 创建一个区域
        MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
        // 设置地图显示区域
        [mapView setRegion:region animated:YES];
        
     
    }];
    
}

#pragma mark 点击此按钮, 返回用户所在的位置
- (void)backUserLocationClick:(id)sender {
    //1. 设置中心点坐标
    //self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;
    
    //2. 设置范围的属性
    //2.1 获取坐标
    CLLocationCoordinate2D coordinate = mapview.userLocation.location.coordinate;
    
    //2.2 设置显示范围 --> 为了跟系统默认的跨度保持一致, 我们可以打印region的span值来获取, 然后设置即可
    //1° ~ 111KM
    MKCoordinateSpan span = MKCoordinateSpanMake(0.021252, 0.014720);
    
    //2.3 设置范围属性 默认没有动画
    //self.mapView.region = MKCoordinateRegionMake(coordinate, span);
    
    //设置范围方法 可以设置动画
    [mapview setRegion:MKCoordinateRegionMake(coordinate, span) animated:YES];
}

/**
 当地图显示区域发生改变后, 会调用的方法
 */
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    //获取默认的显示大小 --> span
    NSLog(@"latitudeDelta : %f, longitudeDelta: %f", mapview.region.span.latitudeDelta, mapview.region.span.longitudeDelta);

}

#pragma mark 放大地图
- (void)zoomInClick:(id)sender {
    //1. Delta 跨度缩小一倍
    //region : 是当前地图显示的区域
    CGFloat latitudeDelta = mapview.region.span.latitudeDelta *0.5;
    CGFloat longitudeDelta =mapview.region.span.longitudeDelta *0.5;
    
    //2. 重设地图region属性
    [mapview setRegion: MKCoordinateRegionMake(mapview.centerCoordinate, MKCoordinateSpanMake(latitudeDelta, longitudeDelta)) animated:YES];
}

#pragma mark 缩小地图
- (void)zoomOutClick:(id)sender {
    //1. Delta 跨度放大一倍
    //region : 是当前地图显示的区域
    CGFloat latitudeDelta = mapview.region.span.latitudeDelta * 2;
    CGFloat longitudeDelta =mapview.region.span.longitudeDelta * 2;
    
    //2. 重设地图region属性
    [mapview setRegion: MKCoordinateRegionMake(mapview.region.center, MKCoordinateSpanMake(latitudeDelta, longitudeDelta)) animated:YES];
}


//设置大头针
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 在地图上操作大头针实际上是操作的大头针数据模型， 删除大头针就是删除大头针数据模型，添加大头针就是添加大头针数据模型
    
    // 获取触摸点所在父视图对应的坐标
    CGPoint point = [[touches anyObject] locationInView:mapview];
    // 根据坐标点获取对应的经纬度
    CLLocationCoordinate2D locationCoordinate2D = [mapview convertPoint:point toCoordinateFromView:mapview];
    
 //   CLLocation *location = [[CLLocation alloc] initWithLatitude:locationCoordinate2D.latitude longitude:locationCoordinate2D.longitude];
    
    MKAnnotation *antion =[[MKAnnotation alloc]init];
    antion.title=@"111";
    antion.subtitle=@"222";
    antion.coordinate = CLLocationCoordinate2DMake(40, 110);
    
  
  
    //地图上设置大图标的经度和纬度
    antion.coordinate = CLLocationCoordinate2DMake(locationCoordinate2D.latitude, locationCoordinate2D.longitude);
    
    //添加大头针到地图中
    
    [mapview addAnnotation:antion];
    
    // 让地图挪动到对应的位置(经纬度交叉处)
    
    [mapview setCenterCoordinate:antion.coordinate animated:YES];

}
//自定义大头针样式 代理方法
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    static NSString *ID = @"ancell";
    
    MKPinAnnotationView *annoView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    
    if (annoView == nil) {
        
        annoView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID];
        
        // 显示气泡
        
        annoView.canShowCallout = YES;
        
        // 设置绿色
        
        annoView.pinColor = MKPinAnnotationColorGreen;
        
    }
    
    return  annoView;
}

@end
